//
//  LWHomeTableViewController.swift
//  Microblog
//
//  Created by Roman on 17/1/4.
//  Copyright © 2017年 Roman. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel

//定义可以重用标示
//原创
private let originalCellID = "LWStatusCellId"
//转发
private let retweetdeCellID = "LWRetweetdeStatuses"
class LWHomeTableViewController: LWBaseTableViewController {

    
    lazy var homeViewModel = LWHomeViewModel()
   let RefreshControl = LWRefreshControl()
    
    
    //懒加载上拉刷新
    lazy var indocatorView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        
        //测试 
       // indicator.startAnimating()
        
        return indicator
    }()
        /*
     如果用户登录,就让为tableView
     如果没有登录 ,跟视图就为访客视图
     */
     
    override func viewDidLoad() {
        super.viewDidLoad()
        //判断用户是否登录.
        if !userLogin {
            //没有登录
            //设置方可视图信息
            visitorLoginView.updateInfo(imageName: "visitordiscover_feed_image_smallicon", title: "关注一些人,看看有什么惊喜关注一些人,看看有什么惊喜关注一些人", isHome: true)
            //return 不写,无法跳出循环
            return
        }
        
        //设置tableVIew 注册
        setupTableView()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "", imageName: "navigationbar_pop", target: self, action: #selector(nextPage))

        loadData()
    }
    
    func loadData() {
        
        self.homeViewModel.loadDate(isPullUp: indocatorView.isAnimating) { (success) in
            
            if !success {
                SVProgressHUD.showError(withStatus: "没有网络,加载错误")
                return
            }
            //刷新数据
            
            //停止动画
            self.RefreshControl.endRefreshing()

            self.indocatorView.stopAnimating()
            self.tableView.reloadData()
            //下拉刷新停止
                        
        }
        
    }
    
    
    private func setupTableView() {
        //注册cell
        //self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: homeCellID)
        let originalCellNib = UINib(nibName: "LWstatusesCell", bundle: nil)
        
        self.tableView.register(originalCellNib, forCellReuseIdentifier: originalCellID)
        
        //注册cell
        let retweetdeCellNib = UINib(nibName: "LWRetweetdeStatuses", bundle: nil)
        self.tableView.register(retweetdeCellNib, forCellReuseIdentifier: retweetdeCellID)
        
        //设置分割线
        tableView.separatorStyle = .none
        //tableView.rowHeight = 800
        //上拉刷新.
        tableView.tableFooterView = indocatorView
//        //使用下拉刷新控件
//        refreshControl = UIRefreshControl()
//        //监听用户下拉刷新操作
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        
        RefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        self.view.addSubview(RefreshControl)
        
    }
    
    
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        //print(view)
    }
    
    //事件的监听跳转
   @objc private func nextPage()  {
        //进入页面
      let demo = LWDemoViewController()
   
      self.navigationController?.pushViewController(demo, animated: true)
    }
 
}

extension LWHomeTableViewController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.homeViewModel.viewmodelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let viewModel = self.homeViewModel.viewmodelArray[indexPath.row]
        
        let cellID = getCellByViewModel(viewModel: viewModel)
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! LWstatusesCell
       // let a = self.homeViewModel.statuses[indexPath.row]
        
        
        cell.viewModel = viewModel
        
        return cell
        
    }
    //行高的计算
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //1.获取cell
        let viewModel = self.homeViewModel.viewmodelArray[indexPath.row]
        
        let cellID = getCellByViewModel(viewModel: viewModel)
        
        let cell = getCellById(id: cellID)
        
        cell.viewModel = viewModel
        
        //强制刷新
        cell.layoutIfNeeded()
        
        //2.返回cell
        return cell.toolBar.frame.maxY
    }
    
    //根据不同的ID 获取不同的cell 对象
    private func getCellById(id: String) -> LWstatusesCell {
        if id == originalCellID {
            //返回原创cell
            let originalCell = UINib(nibName: "LWstatusesCell", bundle: nil).instantiate(withOwner: nil, options: nil).last as! LWstatusesCell
            return originalCell
            
        }
        //返回转发cell
        let retweetdeCell = UINib(nibName: "LWRetweetdeStatuses", bundle: nil).instantiate(withOwner: nil, options: nil).last as! LWstatusesCell
        return retweetdeCell
    }
    
    //在cell将要展示的时候进行加载
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        //预加载数据实现静默加载
        //在倒数第二行的时候进行数据加载
        if indocatorView.isAnimating == false && indexPath.row == self.homeViewModel.viewmodelArray.count - 2 {
            //加载数据
            print("~~~~~~进行数据加载")
            
            indocatorView.startAnimating()
            
            loadData()
        }
        
        
    }
    
    
    
    private func getCellByViewModel(viewModel : LWHomeCellModel) -> (String){
        if viewModel.statuses?.retweeted_status != nil {
            //转发微博
            return retweetdeCellID
        }else{
            //原创微博
            return originalCellID

        }
    }
    
    
    
    
    
}







